/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.application;

import com.jb.framework.Container;
import com.jb.framework.Persistable;
import com.jb.framework.PersistentContext;
import com.jb.web.bean.Page;
import com.jb.web.model.GUID;


public class RootContainer extends Container {
    static private RootContainer rootContainer = new RootContainer();
    static long compId = System.currentTimeMillis();

    /**
     * Creates a new RootContainer object.
     */
    private RootContainer() {
    }

    /**
     * Create a faces page definition.
     *
     * @param ctx runtime context.
     * @param name name of the page, if empty, an auto generated name is used.
     *
     * @return page created.
     */
    public static Page createPage(PersistentContext ctx, String name) {
        if ((name == null) || (name.length() == 0)) {
            name = GUID.getInstance().getNext();
        }

        return (Page) rootContainer.create(ctx, name, Page.class);
    }

    /**
     * Locates a bean by name and class.
     *
     * @param ctx runtime context.
     * @param name id of the bean.
     * @param type class of the bean.
     *
     * @return bean instance by name and class.
     *
     * @throws IllegalArgumentException if name is null or empty.
     */
    public static Object findBeanz(PersistentContext ctx, String name, Class type) {
        if ((name == null) || (name.length() == 0)) {
            throw new IllegalArgumentException("name can not be null");
        }
        return rootContainer.find(ctx, name, type);
    }

    /**
     * Deletes an instance from context persistent manager.
     *
     * @param ctx runtime context.
     * @param obj the object to be deleted.
     */
    public static void remove(PersistentContext ctx, Persistable obj) {
        ctx.getPersistentManager().delete(obj);
    }

    /**
     * Saves a persistable object by the context persistent manager.
     *
     * @param ctx Runtime context.
     * @param obj the object to be saved.
     */
    public static void save(PersistentContext ctx, Persistable obj) {
        ctx.getPersistentManager().save(obj);
    }
}
